﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QLab.UX.Engine;
using System.Windows.Forms;

namespace QLab.UX
{
    public class SolutionManager
    {
        private SolutionManager() 
        {

        }

        private static SolutionManager instance = null;
        public static SolutionManager Instance
        {
            get
            {
                if (SolutionManager.instance == null)
                    SolutionManager.instance = new SolutionManager();
                return SolutionManager.instance;
            }
        }

        private QLabSolution _activeSolution = null;
        public QLabSolution ActiveSolution
        {
            get
            {
                return this._activeSolution;
            }
        }

        private QLabFolder _activeFolder = null;
        public QLabFolder ActiveFolder
        {
            get { return this._activeFolder; }
            set { this._activeFolder = value; }
        }

        public bool CreateSolution(string solutionName, string projectName, string location)
        {
            QLabSolution sln = new QLabSolution(location, solutionName);
            QLabProject prj = new QLabProject(location + projectName + "\\", projectName, sln, true);
            sln.Projects.Add(prj.Name, prj);

            XMLManager.Instance.SaveSolution(sln);
            this._activeSolution = sln;
            this._activeFolder = prj.Folder;
            return true;
        }

        public bool SaveSolution()
        {
            XMLManager.Instance.SaveSolution(this._activeSolution);
            return true;
        }

        public bool LoadSolution(string slnPath)
        {
            this._activeSolution = XMLManager.Instance.LoadSolution(slnPath);
            return true;
        }

        internal void CloseSolution()
        {
            if (this._activeSolution.OpenedFunctions.Count > 0)
            {
                if (this._activeSolution.OpenedFunctions.Values.Any(t => t.Changed))
                {
                    if (MessageBox.Show(MainForm_Resources.SaveAllChangesQuestion, "Warning", MessageBoxButtons.YesNo)
                    == DialogResult.Yes)
                    {
                        foreach (QLabFunction function in this._activeSolution.OpenedFunctions.Values)
                        {
                            function.Save();
                        }
                    }
                }
                foreach (QLabFunction function in this._activeSolution.OpenedFunctions.Values.ToList())
                {
                    function.Close();
                }
            }
            this._activeSolution = null;
        }
    }
}
